<?php
/**
*	使用php的请求
*/

header('Content-type:text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:X-Requested-With');
header('Access-Control-Allow-Credentials:true');

$host 		= '127.0.0.1';
$port 		= '8089'; //
$timeout 	= 30;


//请求方法
$action 	= @$_GET['action'];

//请求类型
$method		= strtoupper($_SERVER['REQUEST_METHOD']);

$type		= 'SOCKET';
if($method=='POST')$type='SOCKETPOST';
if($method=='OPTIONS')exit('OK');

//URL参数
$urlparams 		= '';	
foreach($_GET as $k=>$v){
	if($k!='action')$urlparams.='&'.$k.'='.$v.'';
}
if($urlparams)$urlparams = '?'.substr($urlparams, 1).'';

$handle 	= stream_socket_client('tcp://'.$host.':'.$port.'', $errno, $errstr, $timeout, STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);

$str = "".$type." /".$action.$urlparams." HTTP/1.1\r\n";
$str.= "Connection: keep-alive\r\n";
$str.= "Accept: application/json\r\n";
$str.= "User-Agent: ".$_SERVER['HTTP_USER_AGENT']."\r\n";

$str.= "\r\n";

//以下是POST的数据
if($method=='POST'){
	$postdata = trim(file_get_contents('php://input'));
	$str.= $postdata;
}

fwrite($handle, $str); 

$bstr	 	= '';
$readci 	= 0;
while (!feof($handle)) {
	$bstr .= fread($handle, 1024);
	$readci++;
	if($readci>1024)break;
}

$barr = explode("\r\n\r\n", $bstr);
if(count($barr)>1)$bstr = $barr[1];
fclose($handle);

echo $bstr;